#ifndef _MAIN_C_
#define _MAIN_C_
/*********************************************************************************************************************/
#include "include/ca51f003_config.h"		
#include "include/ca51f003sfr.h"
#include "include/ca51f003xsfr.h"
#include "include/gpiodef_f003.h"
#include "include/system_clock.h"

#include <intrins.h>
#include "include/uart.h"
#include "include/delay.h"
#include "include/adc.h"
#include "include/Beep.h"

#include "include/spi.h"
#include "include/zkrd522.h"
#include "include/iso14443a.h"
#include "include/rfid_interface.h"
#include "mifare.h"
//TMCON定义
#define TME(N)		(N<<7) 	//N=0-1
#define TMF				(1<<0) 
bit IE_EA;

#define UART_SIZE_BUF 256
const unsigned char addr = 0x01;

#define DEBUG 0

typedef struct 
{
	unsigned char  head;
	unsigned char  addr;
	unsigned char  command;
	unsigned char  length; //只记录data数据长度
	unsigned char  buf[UART_SIZE_BUF];
	unsigned char   tail;
	unsigned char   bcc;
}xdata uart_data;
uart_data uart_buffer;
//status 状态码，len数据域长度
void uart_moudleRx(unsigned char status,unsigned char len)
{
	#if DEBUG
    unsigned char i,temp=0;
	uart_printf("RX:%02x %02x %02x ",(int)uart_buffer.head,
		(int)uart_buffer.addr,(int)uart_buffer.command);
	uart_printf("%02x ",(int)status);
	uart_printf("%02x ",(int)len);
	temp ^= uart_buffer.head;
	temp ^= uart_buffer.addr;
	temp ^= uart_buffer.command;
	temp ^= status;
	temp ^= len;
	for(i=0;i<len;i++)
	{
		temp ^= uart_buffer.buf[i];
		uart_printf("%02x ",(int)uart_buffer.buf[i]);
	}
	temp ^= uart_buffer.tail;
	uart_printf("%02x %02x\r\n",(int)uart_buffer.tail,(int)temp);
	
	#else
	
	unsigned char i,temp=0;
	Uart2_PutChar(uart_buffer.head);
	Uart2_PutChar(uart_buffer.addr);
	Uart2_PutChar(uart_buffer.command);
	Uart2_PutChar(status);
	Uart2_PutChar(len);
	temp ^= uart_buffer.head;
	temp ^= uart_buffer.addr;
	temp ^= uart_buffer.command;
	temp ^= status;
	temp ^= len;
	for(i=0;i<len;i++)
	{
		temp ^= uart_buffer.buf[i];
		Uart2_PutChar(uart_buffer.buf[i]);
	}
	temp ^= uart_buffer.tail;
	Uart2_PutChar(uart_buffer.tail);
	Uart2_PutChar(temp);
    #endif
}


static unsigned char uart_flag = 0;
void uart_read_data()
{
	unsigned char data_temp;
	static unsigned char len=0,i,temp=0;
	if(uart_flag != 0xff)
	{
		if(uart2_rev.tail != uart2_rev.head)		//表示有数据待取
		{
			uart2_rev.tail++;
			uart2_rev.tail %= UART2_RX_BUF_SIZE;				
			data_temp=uart2_rx_buf[uart2_rev.tail];
			if(data_temp == 0xAA && uart_flag == 0)
			{
				uart_buffer.head = data_temp;
				uart_flag = 1;
			}
			else if(uart_flag == 1)
			{
				if(data_temp == addr)
				{
					uart_buffer.addr = data_temp;
					uart_flag = 2;
				}
				else
				{
					uart_moudleRx(0x21,0);
					uart_flag = 0;
					uart2_rev.tail = uart2_rev.head;//清零舍弃后面的数据
				}
			}
			else if(uart_flag == 2)
			{
				uart_buffer.command = data_temp;
				uart_flag = 3;
			}
			else if(uart_flag == 3)
			{
				uart_buffer.length = data_temp;
				uart_flag = 4;
				len = data_temp;
				i=0;
				if(len>UART_SIZE_BUF)
				{
					uart_moudleRx(0x22,0);
					uart_flag = 0;
					uart2_rev.tail = uart2_rev.head;//清零舍弃后面的数据
				}
			}
			else if(uart_flag == 4)
			{
				if(len>0)
				{
					uart_buffer.buf[i++] = data_temp;
					len --;
				}
				else
				{
					if(data_temp == 0xBB)
					{
						uart_buffer.tail = data_temp;
						uart_flag = 5;
					}
					else
					{
						uart_moudleRx(0x23,0);
						uart_flag = 0;
						uart2_rev.tail = uart2_rev.head;//清零舍弃后面的数据
					}
				}
			}
			else if(uart_flag == 5)
			{
					uart_buffer.bcc = data_temp;
					temp ^= uart_buffer.head;
					temp ^= uart_buffer.addr;
					temp ^= uart_buffer.command;
					temp ^= uart_buffer.length;
					for(i=0;i<uart_buffer.length;i++)
					{
						temp ^= uart_buffer.buf[i];
					}
					temp ^= uart_buffer.tail;
					if(temp != uart_buffer.bcc)
					{
						uart_moudleRx(0x24,0);
						uart_flag = 0;
						uart2_rev.tail = uart2_rev.head;//清零舍弃后面的数据
					}
					else
					{
						uart_flag = 0xff;
						uart2_rev.tail = uart2_rev.head;
					}
					temp = 0;
			}
		}
	}
}


uint8_t Read_uid(unsigned char *uid)
{
	unsigned char xdata cln,sak; 
	unsigned char xdata status;
	status = get_typeA_card(&cln,uid,&sak);
	if(status != MI_OK)
	{
		spi_write_reg(txcontrol_reg,0x00);//关场
		Delay_ms(10);
		spi_write_reg(txcontrol_reg,0x1b);//开场
		Delay_ms(10);
	}
	return status;
}


void Enter_Stop_Mode()
{
		I2CCON = 0;						//关闭I2C，否则无法关闭主时钟
		SWICON |= 0x01;				//关闭单线通信功能，否则无法关闭主时钟
		CKCON = 0x80;					//其他时钟关闭，IRCL时钟不关闭
		PWCON &= ~0x08;				//设置LDO进入低功率模式
		MECON |= (1<<6); 			//设置 FLASH 进入深度睡眠状态
		while(STPSTH|STPSTL); //如果有中断未响应,等待中断被响应
		IE_EA = EA; 					//保存全局中断使能位状态
		EA = 0;
		PCON |= 0x02;					//进入STOP模式，等待TMC中断唤醒
		_nop_();
		_nop_();
		_nop_();
		EA = IE_EA; 					//恢复原全局中断开关状态	
		PWCON |= 0x08;				//退出STOP模式后，把LDO设回高功率模式
}
	
void TMC_ISR (void) interrupt 13 	  
{
	if(TMCON & TMF)			//毫秒中断
	{
		TMCON |= TMF;	
	}
}	

void test(void);

void main(void)
{
		unsigned char i,status,len = 0;
		unsigned char xdata uid[12];                             //操作块0
		unsigned char xdata block_buf[8] = {0};
		unsigned char xdata send_block[16];
#ifdef LVD_RST_ENABLE
	LVDCON = 0xE0;					//设置LVD复位电压为2V
#endif

#ifdef UART1_EN
	Uart1_Initial(UART1_BAUTRATE);
#endif

#ifdef UART2_EN
	Uart2_Initial(UART2_BAUTRATE);
#endif
	
	EA = 1;							//开全局中断

#ifdef PRINT_EN
	uart_printf("RFID Demo Code\r\n");
#endif
	//ADC_Init();
/**********配置LED引脚***************************************************************/	
//	P17F = OUTPUT;
//	P20F = OUTPUT;
/**********蜂鸣器初始化***************************************************************/	
//	Beep_Init();
/**********配置RD522 RST引脚*********************************************************/
	P14F = OUTPUT; 
	RD522_RST_PIN = 0;
	Delay_ms(10);
	RD522_RST_PIN = 1;
	Delay_ms(10);
 /**********SPI初始化***************************************************************/
	P11F = OUTPUT;
	RD522_EA_PIN = 1;
	P13F = OUTPUT;
	RD522_I2C_PIN = 0;
	spi_init();
	Delay_ms(10);
	spi_init();
	Delay_ms(10);
/**********TMC定时器配置***************************************************************/
//	CKCON |= ILCKE;	//使能IRCL时钟
//	TMCON = TME(1);	//TMC使能
//	TMSNU = 129;			//设置中断时间，中断时间 = TMSNU * 512 * Tircl
//	INT8EN =1;
	RD522_RST_PIN = 0;                     //RST拉高使能
	Delay_50us(24);	
	RD522_RST_PIN = 1;                     //RST拉高使能
	Delay_50us(24);	
	pcd_config('A');
	pcd_set_rate(RATE_106,14);
	Delay_ms(100);
	
	while(1)
	{	
//		test();
		uart_read_data();
		if(uart_flag == 0xff)
		{
			#if DEBUG
            uart_printf("TX:%02x %02x %02x %02x ",(int)uart_buffer.head,(int)uart_buffer.addr,
			(int)uart_buffer.command,(int)uart_buffer.length);
			for(i=0;i<uart_buffer.length;i++)
			{
				uart_printf("%02x ",(int)uart_buffer.buf[i]);
			}
			uart_printf("%02x %02x\r\n",(int)uart_buffer.tail,(int)uart_buffer.bcc);
            #endif
			uart_flag = 0;
			len = 0;
			switch(uart_buffer.command)
			{
				case 0x00://读模块信息
				memcpy(uart_buffer.buf,"RD522V1.0",9);
				len = 9;
				break;
				
				case 0x01: //读uid
				status = Read_uid(uid);//获取uid
				if(status == 0x00)
				{
					memcpy(uart_buffer.buf,uid,8);
					len = 8;
				}
				else
				{
					status = 0xff;
					len = 0;
				}
				break;
				
				case 0x02://读模块
				status = pcd_read_block(uart_buffer.buf[0],block_buf);
				if(status == 0x00)
				{
					memcpy(uart_buffer.buf,block_buf,4);
					len = 4;
				}
				break;
				
				case 0x03://写函数
				memcpy(send_block,&uart_buffer.buf[1],4);
				memset(&send_block[4],0,8);
				status = pcd_write_block(uart_buffer.buf[0],send_block);
				break;
				
				case 0x04: //挂起函数
				status = pcd_halt();
				break;
				
				case 0x05://透传
				status = desocd_transmission(&uart_buffer.length,uart_buffer.buf);
				if(status == 0x00)
				{
					len = uart_buffer.length;
				}
				break;
					
				default :status = 0xfe;break;
			}
			if(status != 0x00)
			{
			//	uart_printf("error\r\n");
			}
			uart_moudleRx(status,len);
			//uart_printf("\r\n");
		}
	}
}

#define DEBUG_3SIZE 0
#define DEBUG_5SIZE 1
unsigned long int error = 0;
void test(void)
{
	unsigned char data_temp;
	unsigned long int i=0,k;
	unsigned char xdata cln,sak,uid[12]; 
	unsigned char xdata status;
	error = 0;
	if(uart2_rev.tail != uart2_rev.head)
	{
		uart2_rev.tail++;
		uart2_rev.tail %= UART2_RX_BUF_SIZE;				
		data_temp=uart2_rx_buf[uart2_rev.tail];
		if(data_temp == 'A')
		{
			#if DEBUG_3SIZE
			for(i=0;i<1000;i++)
			#endif
			#if DEBUG_5SIZE
			for(i=0;i<100000;i++)
			#endif
			{
				uart_printf("size = %ld\r\n",i);
				status = get_typeA_card(&cln,uid,&sak);
				if(0 == status)
				{
					if(i%1000 == 0)
					{
						uart_printf("uid:");
						for(k=0;k<8;k++)
						{
							uart_printf("%02bx ",uid[k]);
						}
						uart_printf("\r\n");
					}
					pcd_halt();
					Delay_ms(5);
				}
				else
				{
					error ++;
					uart_printf("EEPR\r\n");
					spi_write_reg(txcontrol_reg,0x00);//关场
					Delay_ms(10);
					spi_write_reg(txcontrol_reg,0x1b);//开场
					Delay_ms(10);
				}
			}
		}
		
		else if(data_temp == 'B')
		{
			status = get_typeA_card(&cln,uid,&sak);
			if(status == 0x00)
			{
				uart_printf("uid:");
					for(k=0;k<8;k++)
					{
						uart_printf("%02bx ",uid[k]);
					}
					uart_printf("\r\n");
					spi_write_reg(txcontrol_reg,0x00);//关场
					Delay_ms(10);
					spi_write_reg(txcontrol_reg,0x1b);//开场
					Delay_ms(10);
			}
			else
			{
				uart_printf("EEPR\r\n");
				spi_write_reg(txcontrol_reg,0x00);//关场
					Delay_ms(10);
					spi_write_reg(txcontrol_reg,0x1b);//开场
					Delay_ms(10);
			}
		}
		
		uart_printf("error = %ld size = %ld\r\n",error,i);
	}
}

#endif
